package org.moonshiner.ctci.c1.q3;

import java.util.Arrays;

public class PermutationChecker {

	public boolean isPermutation1(String str1, String str2){
		if (str1.length() != str2.length()){
			return false;
		}
		
		return sort(str1.toCharArray()).equals(sort(str2.toCharArray()));
	}
	
	public boolean isPermutation2(String str1, String str2){
		if (str1.length() != str2.length()){
			return false;
		}
		
		int[] letters = new int[256];
		
		for(char c: str1.toCharArray()){
			letters[c]++;
		}
		
		for (int i = 0; i < str2.length(); i++) {
			
			char c = str2.charAt(i);
			
			if(--letters[(int)c] < 0){
				return false;
			}
		}
		
		return true;
	}
	
	private String sort(char[] chars){
		Arrays.sort(chars);
		return new String(chars);
	}
	
}
